import datastructure.binarytree.TreeNode;

import java.util.*;


/*
 * @lc app=leetcode.cn id=107 lang=java
 *
 * [107] 二叉树的层序遍历 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int size;
        TreeNode n;
        List<List<Integer>> result = new ArrayList<>();
        while (!q.isEmpty()) {
            size = q.size();
            List<Integer> level = new ArrayList<>();
            result.add(level);
            for (int i = 0; i < size; i++) {
                n = q.poll();
                level.add(n.val);
                if (n.left != null) {
                    q.offer(n.left);
                }
                if (n.right != null) {
                    q.offer(n.right);
                }
            }
        }
        Collections.reverse(result);
        return result;
    }
}
// @lc code=end
